<template>
  <!-- FBA发货单 -->
  <div class="fulfillmentInbound-list-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button class="gray-outline" v-if="$authPass('procurement.fba.shipment.amazon.edit')" @click="updateFba">更新FBA货件</a-button>
            <a-button class="gray-outline" v-if="$authPass('procurement.fba.shipment.amazon.pull')" @click="showPullDialog = true">拉取FBA货件</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-singe-line"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :data="tableList"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :bordered="true"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="shopName" title="店铺" :width="100" fixed="left">
                <template #cell="{ record }">
                  <TextLimit>{{ record.shopName }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="billNo" title="已绑定发货单" :width="100" fixed="left" />
              <a-table-column data-index="shipmentId" title="FBA货件号" :width="100" />
              <a-table-column data-index="destinationFulfillmentCenterId" title="CenterId" :width="80" />
              <a-table-column data-index="shipmentStatus" title="FBA货件状态" :width="90" />
              <a-table-column data-index="shipFromAddress" title="发货地址" :width="100">
                <template #cell="{ record }">
                  <TextLimit>{{ getAddress(record.shipFromAddress) }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="skuType" title="SKU数" :width="60" />

              <a-table-column data-index="realNum" title="总数量" :width="60">
                <template #cell="{ record }">
                  <a-popover title="货件明细" trigger="click" position="bottom">
                    <p class="highlight cursor">{{ record.realNum }}<icon-down style="margin-left: 5px" /></p>
                    <template #content>
                      <AmazonFbaItems :list="record.inboundShipmentItemList" />
                    </template>
                  </a-popover>
                </template>
              </a-table-column>
              <a-table-column data-index="labelPrepType" title="类型标签" :width="80" />
              <a-table-column data-index="shipmentType" title="发货类型" :width="80" />
              <a-table-column title="承运商/跟踪号" :width="100" key="carrier">
                <template #cell="{ record }">
                  <p>{{ record.carrierName }}</p>
                  <TextLimit :rows="1">{{ record.logisticsTrackNumber }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column title="创建时间" :width="130" key="gmtCreate">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="80" fixed="right" key="handle">
                <template #cell="{ record }">
                  <a-button type="text" v-if="$authPass('procurement.fba.shipment.amazon.labels')" @click="printBox(record)">下载装箱单</a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 打印装箱单 -->
  <PrintFbaBox v-if="showPrintBox" :isShow="showPrintBox" api="getFbaShipmentAmazonPackingLabels" :currentData="currentData" @closed="showPrintBox = false" />
  <!-- 拉取货件 -->
  <PullAmazonFba v-if="showPullDialog" :isShow="showPullDialog" @closed="showPullDialog = false" @success="getTableList" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import AmazonFbaItems from './components/amazonFbaItems.vue'
  import PullAmazonFba from './components/pullAmazonFba.vue'

  import { findFbaShipmentAmazonPage, updateAmazonFbaShipments } from '@/api/purchase'
  import useBaseDataStore from '@/store/modules/base-data'
  import PrintFbaBox from '@/views/warehouse/fbaDelivery/components/printFbaBox.vue'
  onMounted(() => {
    getTableList()
    getShopList()
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'shopId',
      label: '店铺',
      value: ref(),
      type: 'select',
      width: 200,
      optionItems: [],
    },
    {
      type: 'input_keyword',
      key: 'shipmentIds',
      keyItems: [
        { label: '货件ID', value: 'shipmentIds' },
        { label: '发货单号', value: 'billNos' },
      ],
      keyWidth: '110',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'mskus',
      keyItems: [
        { label: 'MSKU', value: 'mskus' },
        { label: 'FNSKU', value: 'fnskus' },
        { label: 'ASIN', value: 'asins' },
        { label: 'SKU', value: 'skus' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },

    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [{ label: '创建日期', value: 'gmtCreate' }],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])

  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const tableRef = ref()
  const filterData = ref<any>({})
  const currentData = ref<any>({})
  const useBaseData = useBaseDataStore()
  const showPrintBox = ref(false)
  const showPullDialog = ref(false)

  // 打印箱单
  function printBox(item: any) {
    currentData.value = item
    showPrintBox.value = true
  }

  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    filterItem.value[0].optionItems = useBaseData.shopList.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
      }
    })
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }

  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findFbaShipmentAmazonPage(params)
    tableRef.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
  }
  // 显示地址
  function getAddress(address: any) {
    return `${address?.countryCode || ''}${address?.stateOrProvinceCode || ''}${address?.city || ''}${address?.addressLine1 || ''}`
  }
  // 确认更新货件
  function updateFba() {
    if (!selectIds.value.length) {
      Message.error('请选择货件')
      return
    }
    Modal.confirm({
      title: '',
      content: `请再次确认是否更新选中货件`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await updateAmazonFbaShipments({ ids: selectIds.value })
        if (res) {
          Message.success('更新成功')
          getTableList()
        }
      },
    })
  }
</script>
<style lang="less" scoped></style>
